<template>
  <div>
    {{msg}}
    <ul class="topTab">
      <li ref="lump" v-for="(item , index, key) in stockBar" @click="chose(key, index)" :class="{'active':choseBar == key}">
        <p :class="{'stockPlus': parseFloat(item.change)>0}">{{item.index}}</p>
        <p>
          <span v-text='getMarket(index)'></span> <span :class="{'stockPlus': parseFloat(item.change)>0}">{{item.change}}</span></p>
      </li>
    </ul>
    <em ref="float"></em>
    <loading :own-state="ownState"></loading>
    <div ref="index" class="index-chart">
    </div>
  </div>
</template>

<script>
  import echarts from 'echarts/lib/echarts';
  import remoteDAO from '@/common/remoteDAO'
  import {getTradeTimeArr, extend, getIndexMaxChg} from '@/common/common'
  import constant from '@/common/constant';
  const tradeDateArr = getTradeTimeArr();
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      show: true,
      left: 0,
      top: 10,
      bottom: 25,
      right: 0,
      borderColor: 'transparent'
    },
    xAxis: [{
      type: 'category',
      data: tradeDateArr,
      boundaryGap: false,
      splitLine: {
        show: true,
        lineStyle: {
          opacity: 0.7,
          type: 'dotted',
          color: '#bac9d8'
        }
      },
      axisPointer: {
        show: true,
        type: 'line',
        lineStyle: {
          type: 'solid'
        },
        label: {
          show: false,
          backgroundColor: 'transparent',
          textStyle: {
            color: 'transparent'
          }
        }
      },
      axisLabel: {
        textStyle: {
          color: '#999999',
          fontSize: 10,
          align: 'center'
        },
        interval: 59,
        formatter: (value, index) => {
          if (index == 0) {
            return '                     ' + tradeDateArr[index];
          } else if (index == 60) {
            return '';
          } else if (index == 180) {
            return '';
          } else if (index == 240) {
            return tradeDateArr[index] + '                     ';
          } else {
            return tradeDateArr[index]
          }
        }
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: '#eeeeee'
        }
      }
    }, {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          type: 'solid',
          color: 'white'
        }
      },
      z: 999
    }],
    yAxis: [{
      z: 999,
      show: true,
      type: 'value',
      boundaryGap: false,
      axisLine: {
        show: true,
        lineStyle: {
          color: 'white',
          type: 'solid'
        }
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        margin: 15,
        inside: true,
        textStyle: {
          fontSize: 10,
          color: '#999999'
        }
      },
      axisTick: {
        show: false
      },
      min: 1500,
      max: 3500,
      interval: 1000
    }, {
      z: 999,
      show: true,
      type: 'value',
      data: [],
      boundaryGap: false,
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        margin: 15,
        inside: true,
        textStyle: {
          fontSize: 10,
          color: '#999999'
        }
      },
      axisTick: {
        show: false
      },
      position: 'right'
    }, {
      z: 999,
      show: true,
      type: 'value',
      data: [],
      boundaryGap: false,
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          opacity: 0.7,
          type: 'dotted',
          color: '#bac9d8'
        }
      },
      axisLabel: {
        show: false
      },
      axisTick: {
        show: false
      },
      position: 'right',
      min: 1500,
      max: 3500,
      interval: 500
    }],
    series: [
      {
        name: '大盘数据',
        type: 'line',
        smooth: true,
        symbol: `image://${require('@/assets/images/blueSymbol.svg')}`,
        showSymbol: false,
        sampling: 'average',
        lineStyle: {
          normal: {
            color: '#BAC9D8',
            width: 1
          }
        },
        areaStyle: {
          normal: {
            color: '#E9F6FD'
          }
        }
      }
    ]
  };
  export default {
    name: 'stock-index',
    data () {
      return {
        msg: '',
        myChart: '',
        choseBar: 0,
        market: 'sh',
        yData: {},
        yPercent: '',
        stockBar: {
          sh: {
            index: '-',
            change: ''
          },
          sz: {
            index: '-',
            change: ''
          },
          cyb: {
            index: '-',
            change: ''
          }
        },
        ownState: true
      }
    },
    methods: {
      slide(callback) {
        this.$refs.float.style.width = this.$refs.lump[this.choseBar].offsetWidth + 'px'
        this.$refs.float.style.left = this.$refs.lump[this.choseBar].offsetLeft + 'px'
        if (callback) {
          this.$refs.float.addEventListener('webkitTransitionEnd', () => {
            callback();
          })
        }
      },
      indexSort(data) {
        return {
          sh: data[constant.IndexEnum.SH],
          sz: data[constant.IndexEnum.SZ],
          cyb: data[constant.IndexEnum.CYB]
        }
      },
      chose (key, index) {
        if (this.choseBar == key) return;

        this.ownState = true;
        if (this.choseBar !== key) {
          this.market = index;
          this.choseBar = key
        };
        this.slide(() => {
          this.$loop.register(this.getIndex);
          this.$store.dispatch('choseStockIndex', key);
        });
      },
      getMarket (index) {
        switch (index) {
          case 'sh':
            return '上证指数';
          case 'sz':
            return '深证指数';
          case 'cyb':
            return '创业板指';
        }
      },
      //  获取沪市／深市／创业板 实时行情指数
      getTimeQuotes () {
        let vm = this;
        remoteDAO.getIndexData().then(function (result) {
          console.log(result)
          vm.stockBar = vm.indexSort(result.data);
        })
      },
      // 获取当日从开盘到当前时间的指数行情
      getIndex () {
        let vm = this;
        remoteDAO.getIndexMinList(vm.market).then(function (result) {
          vm.getTimeQuotes();
          var chgRng = Number(getIndexMaxChg(result.data));
          let initData = result.data.index;
          let closeData = result.data.closing;
          let max = (chgRng / 100 + 1) * closeData;
          let min = (1 - chgRng / 100) * closeData;
          let yValue;
          let yValueR;
          let object = extend(option, {
            tooltip: {
              formatter: function (params) {
                return `${vm.choseBar == 0 ? '上证指数' : vm.choseBar == 1 ? '深证指数' : '创业板指数'}<br/>
                  ${params[0].axisValue}&nbsp;&nbsp;${params[0].data[1]}`
              }
            },
            yAxis: [{
              min: min,
              max: max,
              interval: (max - closeData) / 4,
              axisLabel: {
                formatter: (value, index) => {
                  if (index == 0) {
                    yValue = value;
                    return ''
                  } else if (index == 1) {
                    value = yValue;
                    return value.toFixed(2)
                  } else if (index == 4) {
                    return value.toFixed(2)
                  } else if (index == 8) {
                    return value.toFixed(2)
                  }
                }
              }
            }, {
              min: min,
              max: max,
              interval: (max - closeData) / 4,
              axisLabel: {
                formatter: (value, index) => {
                  if (index == 0) {
                    yValueR = ((value - closeData) / closeData * 100).toFixed(2) + '%';
                    return ''
                  } else if (index == 1) {
                    value = yValueR;
                    return value
                  } else if (index == 4) {
                    return ((value - closeData) / closeData * 100).toFixed(2) + '%'
                  } else if (index == 8) {
                    return ((value - closeData) / closeData * 100).toFixed(2) + '%'
                  }
                }
              }
            }],
            series: [{
              data: initData.map((item, index) => [index + 1, item])
            }]
          });
          let date = new Date();
          if (date.getHours() == 9 && date.getMinutes() < 30) {
            object = extend(object, {
              yAxis: [{
                axisLabel: {
                  show: false
                }
              }, {
                axisLabel: {
                  show: false
                }
              }]
            })
          }
          if (!vm.myChart) {
            vm.myChart = echarts.init(vm.$refs.index);
          }
          vm.myChart.setOption(object);
          vm.ownState = false
        }).catch(reason => {
          vm.ownState = false
        })
      }
    },
    mounted () {
      const vm = this;
      vm.$nextTick(function () {
        vm.choseBar = vm.$store.state.stockIndexMsg;
        // vm.myChart = echarts.init(vm.$refs.index);
        vm.slide();
      })
    },
    activated () {
      this.$loop.register(this.getIndex);
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
  @import '~assets/css/variables.less';
  *{
    margin: 0px;
    padding:0px;
  }
  div{
    position: relative;
    .loading{
      position: absolute;
      bottom: 0;
      height: 1.5rem;
    }
    em {
      transition: .3s ease all;
      content: '';
      position: relative;
      bottom: 2px;
      display: block;
      height: 2px;
      background: #2f9fe9;
    }
    .topTab{
      height:auto;
      display:flex;
      flex-direction:row;
      flex-wrap:nowrap;
      justify-content: center;
      border-bottom:  solid 1px #eaeaea;
    }
    li{
      color: #4a4a4a;
      width: 32%;
      list-style:none;
      line-height: 0.5rem;
      padding-top: 0.06rem;
      padding-bottom: 0.06rem;
      p{
        height: auto;
        width:80%;
        margin: 0 auto;
        line-height: 0.25rem;
        font-size: 0.16rem;
        font-family : HelveticaNeueDeskInterface;
      }
      p:first-child{
        color:@green-a;
      }
      p:last-child{
        font-size:0.12rem;
        font-family : PingFangSC-Regular;
        span:nth-child(1){
          font-family : HelveticaNeueDeskInterface-Regular;
        }
        span:nth-child(2){
          color:@green-a;
          font-family : HelveticaNeueDeskInterface-Regular;
        }
      }
      .stockPlus{
        color:#eb333b !important;
      }
    }
    .index-chart {
      height:1.5rem;
      margin-top: 1px;
    }
  }

  .active{
    p:last-child{
      span:first-child{
        color:@blue-a;
      }
    }
    // border-bottom: 2px @blue-a solid;
  }
</style>
